//
//  ConfirmCarVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/7/25.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ConfirmCarVC.h"
#import "Header.h"
#import "Common.h"
#import <Masonry.h>
#import "ConfirmCarVCCell.h"
#import "FindQuoteVC.h"
#import "HomeViewController.h"
#import "WKProgressHUD.h"

@interface ConfirmCarVC ()
{
    UIImageView * nav;
    Common * com;
    UITableView * table;
    NSMutableArray * MoneyNameArr;
    NSMutableArray * MoneyArr;
    UIView * backView;
    NSTimer * timer;
    int submitTime;
}
@property (nonatomic,strong) UIView * submitView;
@property (nonatomic,strong) UILabel * priceAllLabel;
@property (nonatomic,strong) UIView * priceAllLine;
@property (nonatomic,strong) UILabel * activityLabel;
@end

@implementation ConfirmCarVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.moneyDic = [[NSMutableDictionary alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    com = [[Common alloc]init];
    self.view.backgroundColor = GrayColor;
    nav = [self createNav:@"费用详情"];
    [self.view addSubview:nav];
    // 侧滑回到placeorderVC
    self.isOrder = YES;
    _priceAllLabel = [com createUIlabel:@"" andFont:FontOfSize12 andColor:carScrollColor];
    _priceAllLine = [[UIView alloc]init];
    _activityLabel = [com createUIlabel:@"" andFont:FontOfSize12 andColor:YellowColor];
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(pressBackKeep) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    [self.view addSubview:backBtn];
    [backBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nav.mas_left);
        make.centerY.mas_equalTo(nav.mas_top).with.offset(15*kHeight);
        make.size.mas_equalTo(CGSizeMake(60*kWidth, 40*kHeight));
    }];

    
    submitTime = 5;
    MoneyNameArr = @[@"提车费",
                     @"交车费",
                     @"运输费",
                     @"保险费"].mutableCopy;
    MoneyArr = [[NSMutableArray alloc]init];
//    [MoneyArr addObject:self.moneyDic[@"extractcost"]];
//    [MoneyArr addObject:self.moneyDic[@"returncost"]];
//    [MoneyArr addObject:self.moneyDic[@"shippingfee"]];
//    [MoneyArr addObject:_moneyDic[@"insurance"]];
    [MoneyArr addObject:self.moneyDic[@"fees"][0]];
    [MoneyArr addObject:self.moneyDic[@"fees"][1]];
    [MoneyArr addObject:self.moneyDic[@"fees"][2]];
    [MoneyArr addObject:_moneyDic[@"fees"][3]];
    

    
    
    
    
    backView = [[UIView alloc]init];
    backView.backgroundColor = WhiteColor;
    [self.view addSubview:backView];
    

    
    UIView * moneyView = [[UIView alloc]init];
    moneyView.backgroundColor = headerBackViewColor;
    [backView addSubview:moneyView];
    [moneyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backView.mas_left);
        make.top.mas_equalTo(backView.mas_top);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 43*kHeight));
    }];
    
    UILabel * money = [com createUIlabel:@"费用" andFont:FontOfSize14 andColor:BlackTitleColor];
    [moneyView addSubview:money];
    [money mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(moneyView.mas_left).with.offset(18*kWidth);
        make.centerY.mas_equalTo(moneyView.mas_top).with.offset(21.5*kHeight);
    }];
    UIView * line = [[UIView alloc]init];
    line.backgroundColor = LineGrayColor;
    [backView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backView.mas_left);
        make.centerY.mas_equalTo(backView.mas_top).with.offset(43*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
    }];
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, Main_Width, 172*kHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.userInteractionEnabled = NO;
    [backView addSubview:table];
    [table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backView.mas_left);
        make.top.mas_equalTo(line.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 44*kHeight*[self.moneyDic[@"fees"] count]));
    }];
    //initWithFrame:CGRectMake(0, 64, Main_Width, 302*kHeight)];

    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.mas_equalTo(self.view.mas_top).with.offset(64);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 44*kHeight*[self.moneyDic[@"fees"] count]+88*kHeight));
    }];

    
    
    float moneyAll = [self.moneyDic[@"actualtotal"] floatValue];
    UILabel * allMoney = [com createUIlabel:[NSString stringWithFormat:@"￥%.2f",moneyAll] andFont:FontOfSize14 andColor:YellowColor];
    [backView addSubview:allMoney];
    [allMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(backView.mas_right).with.offset(-15*kHeight);
        make.centerY.mas_equalTo(table.mas_bottom).with.offset(21.5*kHeight);
    }];
    
    UILabel * AllPrice = [com createUIlabel:@"总运价" andFont:FontOfSize14 andColor:carScrollColor];
    [backView addSubview:AllPrice];
    [AllPrice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backView.mas_left).with.offset(18*kHeight);
        make.centerY.mas_equalTo(table.mas_bottom).with.offset(21.5*kHeight);
    }];
    
    UIButton * SubmitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [SubmitBtn setTitle:@"确定发车" forState:UIControlStateNormal];
    [SubmitBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [SubmitBtn addTarget:self action:@selector(pressCarBtn) forControlEvents:UIControlEventTouchUpInside];
    SubmitBtn.layer.cornerRadius = 5;
    SubmitBtn.layer.borderWidth = 0.5;
    SubmitBtn.layer.borderColor = YellowColor.CGColor;
    SubmitBtn.backgroundColor = YellowColor;
    [self.view addSubview:SubmitBtn];


    NSString * isdiscount = [NSString stringWithFormat:@"%@",_moneyDic[@"activity"][@"discount"]];
    //优惠
    if ([ isdiscount isEqualToString:@"1"]) {
        
        float total = [self.moneyDic[@"total"] floatValue];
        _priceAllLabel.text = [NSString stringWithFormat:@"￥%.2f",total];
        [backView addSubview:_priceAllLabel];
        [_priceAllLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(allMoney.mas_left).with.offset(-16*kHeight);
            make.bottom.mas_equalTo(allMoney.mas_bottom);
        }];
        
        _priceAllLine.backgroundColor = BlackColor;
        [_priceAllLabel addSubview:_priceAllLine];
        [_priceAllLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_priceAllLabel.mas_left);
            make.right.equalTo(_priceAllLabel.mas_right);
            make.centerY.mas_equalTo(_priceAllLabel.mas_centerY);
            make.height.mas_equalTo(0.5);
        }];
        _activityLabel.text =  [NSString stringWithFormat:@"%@",self.moneyDic[@"activity"][@"desc"]];
        [self.view addSubview:_activityLabel];
        [_activityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.top.mas_equalTo(backView.mas_bottom).with.offset(9*kHeight);
        }];
        [SubmitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.size.mas_equalTo(CGSizeMake(293*kWidth, 40*kHeight));
            make.top.mas_equalTo(_activityLabel.mas_bottom).with.offset(30*kHeight);
        }];
    }else{
        [SubmitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.size.mas_equalTo(CGSizeMake(293*kWidth, 40*kHeight));
            make.top.mas_equalTo(allMoney.mas_bottom).with.offset(30*kHeight);
        }];
    }
    [table reloadData];
    _submitView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, Main_height)];
    _submitView.hidden = YES;
    [self.view addSubview:_submitView];
    [self createSubmitView];
}


-(void)pressBackKeep{
    
    [self createBackUIAlertController:@"确定发车吗？"];
    
}
-(void)createSubmitView{
    
    _submitView.hidden = YES;;
    _submitView.backgroundColor = RGBACOLOR(0, 0, 0, 0.7);
    _submitView.layer.cornerRadius = 5;
    timer= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(pushVC) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    submitTime = 5;
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = WhiteColor;
    [_submitView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_submitView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(231*kWidth, 115*kHeight));
        make.centerY.mas_equalTo(_submitView.mas_centerY);
    }];
    UILabel * labelSumit = [com createUIlabel:@"发车信息发布成功" andFont:FontOfSize15 andColor:YellowColor];
    [view addSubview:labelSumit];
    
    [labelSumit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(view.mas_centerX);
        make.top.mas_equalTo(view.mas_top).with.offset(37*kHeight);
    }];
    UIView * line = [[UIView alloc]init];
    line.backgroundColor = GrayColor;
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(view.mas_centerX);
        make.top.mas_equalTo(view.mas_top).with.offset(77*kHeight);
        make.size.mas_equalTo(CGSizeMake(231*kWidth, 0.5));
    }];
    UIButton * btn1 = [self createBtn:@"继续发布"];
    btn1.layer.borderWidth = 0;
    [btn1 setTitleColor:littleBlackColor forState:UIControlStateNormal];
    btn1.tag = 66;
    [btn1 addTarget:self action:@selector(pressSubmitBtn:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn1];
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line.mas_top);
        make.size.mas_equalTo(CGSizeMake(231/2*kWidth, 38*kHeight));
        make.left.mas_equalTo(view.mas_left);
    }];
    UIButton * btn2 = [self createBtn:@"查看发单(5s)"];
    btn2.layer.borderWidth = 0;
    [btn2 setTitleColor:WhiteColor forState:UIControlStateNormal];
    btn2.tag = 67;
    btn2.backgroundColor = YellowColor;
    [btn2 addTarget:self action:@selector(pressSubmitBtn:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn2];
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line.mas_top);
        make.size.mas_equalTo(CGSizeMake(231/2*kWidth, 38*kHeight));
        make.right.mas_equalTo(view.mas_right);
    }];
}
-(void)pressSubmitBtn:(UIButton*)sender{
    
    if (sender.tag == 67) {
        FindQuoteVC * quote = [[FindQuoteVC alloc]init];
        [timer invalidate];
//        self.isOrder = YES;
        self.isTwo = YES;
        [self.navigationController pushViewController:quote animated:YES];
    }else{
        
        if (_callBack) {
            self.callBack(YES);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)pushVC{
    if (!_submitView.hidden) {
        submitTime--;
        UIButton * btn = (UIButton*)[_submitView viewWithTag:67];
        NSString * string = [NSString stringWithFormat:@"查看发单(%ds)",submitTime];
        [btn setTitle:string forState:UIControlStateNormal];
        if (submitTime==0) {
            FindQuoteVC * quote = [[FindQuoteVC alloc]init];
            [self.navigationController pushViewController:quote animated:YES];
            _submitView.hidden = YES;
            [timer invalidate];
        }
    }
}


-(void)pressCarBtn{
    
    NSDictionary * dic = @{@"id":self.moneyDic[@"id"]};
    
    WKProgressHUD * hud = [WKProgressHUD showInView:self.view withText:@"请稍等" animated:YES];

    [com afPostRequestWithUrlString:Order_Publish_Url parms:dic finishedBlock:^(id responseObj) {
        
        NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        NSString * success = [NSString stringWithFormat:@"%@",dicObj[@"success"]];
        if ([success isEqualToString:@"1"]) {
            
            [hud dismiss:YES];
            
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self createUIAlertController:@"发车成功"];
                
            });

            
            NSLog(@"%@",dicObj);
//            _submitView.hidden = NO;
//            UIButton * btn = (UIButton*)[_submitView viewWithTag:67];
//            NSString * string = [NSString stringWithFormat:@"查看发单(5s)"];
//            [btn setTitle:string forState:UIControlStateNormal];
        }else{
            NSLog(@"message==%@",dicObj[@"message"]);
        }
    } failedBlock:^(NSString *errorMsg) {
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str=@"str";
    ConfirmCarVCCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[ConfirmCarVCCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
    cell.CarLabel.text =[NSString stringWithFormat:@"%@",self.moneyDic[@"fees"][indexPath.row][@"feeName"]];
    NSString * money = [NSString stringWithFormat:@"%@",self.moneyDic[@"fees"][indexPath.row][@"actualAmount"]];
    cell.CarAllPrice.text = [NSString stringWithFormat:@"￥%.2f",[money floatValue]];
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 43*kHeight;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.moneyDic[@"fees"] count];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)createUIAlertController:(NSString*)title
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"返回首页" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        

        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[HomeViewController class]]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"继续发单" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if (_callBack) {
            self.callBack(YES);
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}


-(void)createBackUIAlertController:(NSString*)title
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"去意已决" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BackVC" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
        

        

    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"我再想想" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

-(UIButton*)createBtn:(NSString*)title {
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.layer.borderWidth = 0.5;
    btn.layer.borderColor = littleBlackColor.CGColor;
    btn.titleLabel.font = Font(FontOfSize13);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:BlackColor forState:UIControlStateNormal];
    return btn;
}


@end
